package com.gzc.demo.config;

import com.gzc.demo.authentication.AuthenctiationFailureHandler;
import com.gzc.demo.authentication.AuthenticationSuccessHandler;
import com.gzc.demo.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.gzc.demo.validate.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
//@EnableResourceServer
public class ResouseServerConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	AuthenticationSuccessHandler authenticationSuccessHandler;
	@Autowired
	AuthenctiationFailureHandler authenctiationFailureHandler;
	@Autowired
	ValidateCodeFilter validateCodeFilter;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	PasswordEncoder passwordEncoder;

	@Autowired
	SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

	@Override
	public void configure(HttpSecurity http) throws Exception {

		http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
				.apply(smsCodeAuthenticationSecurityConfig)
				.and()
				.formLogin()
				.loginPage("/imooc-signIn.html")
				.loginProcessingUrl("/authentication/form")
				.successHandler(authenticationSuccessHandler)
				.failureHandler(authenctiationFailureHandler).and()
				.authorizeRequests()
				.antMatchers(
						"/code/**",
						"/user/regist","/imooc-signIn.html","/oauth/authorize",
						"/oauth/token","/oauth/token_key")
				.permitAll()
				.anyRequest()
				.authenticated()
				.and()
				.csrf().disable();

	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
	}
}
